#include "ProfileCon.h"

ProfileCon::ProfileCon()
{
	//ctor
}

ProfileCon::~ProfileCon()
{
	//dtor
}

int ProfileCon::loadTxtFile(const char *path)
{
	ifstream ifs(path);
	if (ifs.good()==false) return 1;
	string line,objId,attName,attVal;
	int index=0,pos;
	//map<string,string> attrs;
	while (getline(ifs,line))
	{
		int len=line.length();
		if (line[0]=='[' && line[len-1]==']')
		{
			//if (!attrs.empty()) Datas[objId]=attrs;
			//attrs.clear();
			objId=line.substr(1,4);
			if (idStrMap.count(objId)==0)
			{
				index=idStrMap.size()+1;
				idStrMap[objId]=index;
				indexMap[index]=objId;
			}
			else
				index=idStrMap[objId];
			continue;
		}
		pos=line.find('=',0);
		if (pos<0) continue;
		attName=line.substr(0,pos);
		if (pos>=len-1) attVal="";
		else attVal=line.substr(pos+1);
		(txtDatas[index])[attName]=attVal;
	}
	return 0;
}

int ProfileCon::saveTxtFile(const char *path)
{
	ofstream ofs(path);
	map<int,map<string,string> >::iterator msmiter;
	map<string,string>::iterator mssiter,mssbeg,mssend;
	ofs.put(0xEF);
	ofs.put(0xBB);
	ofs.put(0xBF);
	for (msmiter=txtDatas.begin(); msmiter!=txtDatas.end(); msmiter++ )
	{
		ofs<<"["<<indexMap[(*msmiter).first]<<"]"<<endl;
		mssbeg=(*msmiter).second.begin();
		mssend=(*msmiter).second.end();
		for (mssiter=mssbeg; mssiter!=mssend; mssiter++)
		{
			ofs<<(*mssiter).first<<"="<<(*mssiter).second<<endl;
		}
	}
	return 0;
}
string ProfileCon::getProfileData(string objId,string attr)
{
	if (idStrMap.count(objId)==0) return "ERR_OBJ_NOT_EXIST";
	int index=idStrMap[objId];
	if ( txtDatas[index].count(attr)==0 ) return "ERR_ATTR_NOT_EXIST";
	return (txtDatas[index])[attr];
}
bool ProfileCon::setProfileDataNotInsert(string objId,string attr,string value)
{
	if (idStrMap.count(objId)==0) return false;
	int index=idStrMap[objId];
	if ( txtDatas[index].count(attr)==0 ) return false;
	(txtDatas[index])[attr]=value;
	return true;
}
bool ProfileCon::setProfileData(string objId,string attr,string value)
{
	int index;
	bool insert;
	if (idStrMap.count(objId)!=0)
	{
		index=idStrMap[objId];
		insert=false;
	}
	else
	{
		index=idStrMap.size()+1;
		idStrMap[objId]=index;
		indexMap[index]=objId;
		insert=true;
	}
	(txtDatas[index])[attr]=value;
	return insert;
}
